package org.misty.blog.controller;

import org.misty.blog.po.Article;
import org.misty.blog.po.Category;
import org.misty.blog.service.ArticleService;
import org.misty.blog.service.CategoryService;
import org.misty.blog.vo.ArticleQuery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class CategoryViewController {
    private final ArticleService articleService;
    private final CategoryService categoryService;

    public CategoryViewController(ArticleService articleService, CategoryService categoryService) {
        this.articleService = articleService;
        this.categoryService = categoryService;
    }

    @GetMapping("/categories")
    public String categoryView(
            @PageableDefault(size = 2, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
            @RequestParam(required = false) Long cateId,
            Model model
    ) {
        List<Category> categories = categoryService.listTop(Integer.MAX_VALUE);
        model.addAttribute("categories", categories);
        if (cateId == null && categories.size() > 0) {
            cateId = categories.get(0).getId();
        }
        if (cateId != null) {
            model.addAttribute("categoryId", cateId);
            ArticleQuery query = ArticleQuery.builder().categoryId(cateId).build();
            Page<Article> page = articleService.listArticles(pageable, query);
            model.addAttribute("page", page);
            model.addAttribute("articles", page.getContent());
        }
        return "types";
    }
}
